from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect, reverse
from django.contrib.auth.views import auth_logout, auth_login
# Create your views here.
from .forms import LoginForm
from .models import CustomUser, WeiBoUser
import requests
import random
from django.core.mail import send_mail

def login(request):
    lgf = LoginForm()
    if request.method == "POST":
        lgf = LoginForm(request.POST)
        if lgf.is_valid():
            print(lgf.cleaned_data["username"], lgf.cleaned_data["password"])
            user = CustomUser.objects.filter(username=lgf.cleaned_data["username"]).first()
            if user:
                auth_login(request, user)
                return redirect(to=reverse("main:index"))
        else:
            print(lgf.errors)
    return render(request, "user/login.html", context={"lgf": lgf})


def logout(request):
    auth_logout(request)
    # request.session.flush()
    return redirect(reverse("main:index"))

def register(request):
    if request.method == 'POST':
        # 获取表单数据
        email = request.POST.get('email')
        password = request.POST.get('password')
        # confirm_password = request.POST.get('confirm_password')
        # nickname = request.POST.get('nickname')
        # phone = request.POST.get('phone')
        captcha = request.POST.get('captcha')

        # 这里应该有更多的验证逻辑，比如密码强度、邮箱格式等

        # 检查验证码是否正确
        if request.session.get('captcha') and request.session['captcha'] == captcha:
            # 创建用户
            user = User.objects.create_user(username=email, email=email, password=password)
            user.save()
            # 登录用户
            login(request, user)
            # 重定向到首页或其他页面
            return redirect(reverse(''))
        else:
            # 验证码错误，返回错误信息
            return render(request, 'user/register.html', {'error': '验证码错误'})
    else:
        return render(request, 'user/register.html')

def send_captcha(request):
    email = request.GET.get('email')
    if email:
        # 生成验证码
        captcha = random.randint(100000, 999999)
        # 将验证码保存到session中，实际应用中应考虑更安全的存储方式
        request.session['captcha'] = captcha
        # 发送验证码邮件
        send_mail(
            '注册验证码',
            f'您的注册验证码是：{captcha}',
            '2335832604@qq.com',  # 发送者邮箱
            [email],  # 接收者邮箱列表
            fail_silently=False,
        )
        # 返回JSON响应
        return JsonResponse({'success': True})
    else:
        return JsonResponse({'success': False, 'error': '邮箱不能为空'})


def check_username(request):
    username = request.GET.get("username")
    if CustomUser.objects.filter(username=username).exists():
        return JsonResponse({
            "code": 0,
            "msg": "成功"
        })
    else:
        return JsonResponse({
            "code": -1001,
            "msg": "用户名不存在"
        })


def auth(request):
    code = request.GET.get("code")
    data = {
        "client_id": "3223537156",
        "client_secret": "a0ba41acf92dd5d1d0c83be6321d4fda",
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:8000/user/auth/",
    }
    res = requests.post("https://api.weibo.com/oauth2/access_token", data=data)
    uid = res.json()['uid']
    print(uid)

    wb_user = WeiBoUser.objects.filter(uid=uid).first()
    if wb_user:
        user = wb_user.cu
        auth_login(request, user)
    else:
        user = CustomUser.objects.create_user(username=f"微博_{uid}", password="123456")
        wb_user = WeiBoUser()
        wb_user.uid = uid
        wb_user.cu = user
        wb_user.save()
    auth_login(request, user)
    return redirect(to=reverse("main:index"))


# token = res.json()['access_token']

# data2 = {
# 	"access_token": token
# }
# res2 = requests.post("https://api.weibo.com/oauth2/get_token_info", data=data2)
#
# print(res2.json())

# return JsonResponse({
# 	"code": 0,
# 	"msg": code
# })
"""
1.微博开放平台开发者认证
2.创建应用
3. 基本信息：获取appkey 和app Secret
4. 测试信息：添加测试账号
5. 高级信息添加回调地址
6. 查看文档 Web网站 OAuth2.0授权，与微博登录组件。 
理解每一个接口的作用
接口一
https://api.weibo.com/oauth2/authorize
dd0535f0ab268e8b0e1b06e4051d67ac  每一次都不一样
接口二
https://api.weibo.com/oauth2/access_token
access_token 2.009Gz5qBmQdJWD97872972eacXoRgC  有效期内不变
uid 1690457060 核心信息 每一个新浪微博唯一信息
接口三
https://api.weibo.com/oauth2/get_token_info


"""
